package com.sunday.pinxinghui.model.account;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.sunday.common.alipay.PayResult;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.ToastUtils;
import com.sunday.pinxinghui.R;
import com.sunday.pinxinghui.base.BaseApplication;
import com.sunday.pinxinghui.base.Constant;
import com.sunday.pinxinghui.entity.PrePay;
import com.sunday.pinxinghui.model.order.OrderListActivity;
import com.sunday.pinxinghui.model.order.OrderPayActivity;
import com.sunday.pinxinghui.network.ApiClient;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by 刘涛 on 2017/8/10.
 */

public class RechargeActivity extends BaseActivity {


    @Bind(R.id.title_view)
    TextView titleView;
    @Bind(R.id.edit_money)
    EditText editMoney;
    @Bind(R.id.alipay)
    CheckBox alipay;
    @Bind(R.id.wechat_pay)
    CheckBox wechatPay;
    @Bind(R.id.btn_submit)
    TextView btnSubmit;
    @Bind(R.id.balance_money)
    TextView balanceMoney;
    private int payType = 2;

    private String balance;
    private IWXAPI api;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recharge);
        ButterKnife.bind(this);
        titleView.setText("充值");
        balance = getIntent().getStringExtra("balance");
        balanceMoney.setText(balance);
        alipay.setChecked(true);
        CheckChangedListener checkChangedListener = new CheckChangedListener();
        alipay.setOnCheckedChangeListener(checkChangedListener);
        wechatPay.setOnCheckedChangeListener(checkChangedListener);
        api = WXAPIFactory.createWXAPI(this, Constant.APP_ID);
        api.registerApp(Constant.APP_ID);
    }


    private class CheckChangedListener implements CompoundButton.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                alipay.setChecked(false);
                wechatPay.setChecked(false);
                switch (buttonView.getId()) {
                    case R.id.alipay:
                        alipay.setChecked(true);
                        payType = 2;
                        break;
                    case R.id.wechat_pay:
                        wechatPay.setChecked(true);
                        payType = 1;
                        break;
                }
            } else {
                payType = 0;
            }
        }
    }

    private PrePay payInfo;
    @OnClick(R.id.btn_submit)
    void submit() {
        String edMoney = editMoney.getText().toString().trim();
        if (TextUtils.isEmpty(edMoney)) {
            ToastUtils.showToast(mContext, "请输入充值金额");
            return;
        }
        if (payType==0){
            ToastUtils.showToast(mContext, "请选择支付方式");
            return;
        }

        showLoadingDialog(0);
        Call<ResultDO<PrePay>> call= ApiClient.getApiAdapter().recharge(BaseApplication.getInstance().getMember().getId(),payType,edMoney);
        call.enqueue(new Callback<ResultDO<PrePay>>() {
            @Override
            public void onResponse(Call<ResultDO<PrePay>> call, Response<ResultDO<PrePay>> response) {
                if (isFinish||response.body()==null){return;}
                if (response.body().getCode()==0) {
                    payInfo=response.body().getResult();
                    switch (payType) {
                        case 1:
                            wechatPay();
                            break;
                        case 2:
                            alipay();
                            break;
                    }
                }else {
                    ToastUtils.showToast(mContext,response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<PrePay>> call, Throwable t) {
                ToastUtils.showToast(mContext,R.string.network_error);
            }
        });
    }

    private void wechatPay() {
        PayReq req = new PayReq();
        req.appId = payInfo.getAppId();
        req.partnerId = Constant.PARTER_ID;
        req.prepayId = payInfo.getPrepayId();
        req.nonceStr = payInfo.getNonceStr();
        req.timeStamp = payInfo.getTimeStamp();
        req.packageValue = "Sign=WXPay";
        req.sign = payInfo.getPaySign();
        req.extData = "app data";
        api.sendReq(req);
        dissMissDialog();
    }


    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_CHECK_FLAG = 2;
    private void alipay() {
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(RechargeActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo.getAlipayString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
        dissMissDialog();
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    //Log.e("支付宝信息",payResult.toString());
                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    String resultInfo = payResult.getResult();

                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Toast.makeText(mContext, "支付成功",
                                Toast.LENGTH_SHORT).show();
                        intent = new Intent(mContext, PurseActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(mContext, "支付结果确认中",
                                    Toast.LENGTH_SHORT).show();

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(mContext, "支付失败",
                                    Toast.LENGTH_SHORT).show();

                        }
                    }
                    break;
                }
                case SDK_CHECK_FLAG: {
                    Toast.makeText(mContext, "检查结果为：" + msg.obj,
                            Toast.LENGTH_SHORT).show();
                    break;
                }
                default:
                    break;
            }
        }

    };


}
